<?php

//验证请求头
$usertoken = empty($_SERVER['HTTP_USERTOKEN']) ? '' : $_SERVER['HTTP_USERTOKEN'];
$user_info = _user_info($usertoken);
$user_id   =  $user_info['user_id'];
if(!$user_info || $usertoken == '') to_ajax(0,'100');
$cachekey_cart = $usertoken.':cart'; //购物车缓存数据



function user_info(){
    global $dou,$user_id;
	$sql = "SELECT * FROM " . $dou->table('user') . " WHERE usertoken='{$GLOBALS[usertoken]}' LIMIT 1";
	$arr = $dou->get_row($sql);
    $arr['coupon_num'] = $dou->get_one("SELECT count(*) count FROM ".$dou->table('coupon')." WHERE user_id='$user_id' LIMIT 1");
	to_ajax(1, '000', $arr);
}

function user_update(){
    global $dou, $user_info, $check, $usertoken;
    $param = array();
    if(i('diner_num','','post') != '')     $param['diner_num'] = i('diner_num','','post');
    if(i('nick_name','','post') != '')     $param['nick_name'] = i('nick_name','','post');
    if(i('admin_name','','post') != '')     $param['admin_name'] = i('admin_name','','post');
    if(i('sex','','post') != '')           $param['sex'] = i('sex','','post');
    if(i('mobile','','post') != '')        $param['mobile'] = i('mobile','','post');
    if(i('invoice_title','','post') != '') $param['invoice_title'] = i('invoice_title','','post');
    if(i('new_password','','post') != '')  $param['password'] = md5(i('new_password','','post'));

    if($param['mobile'] != '' && !$check->is_telphone($param['mobile'])) to_ajax(0,'105');
    if(_check_user_hasfield('mobile',$param['mobile'])) to_ajax(0,'104');
    if($param['password'] != ''){
        $old_password     = md5(i('old_password','','post'));
        $confirm_password = md5(i('confirm_password','','post'));
        if($confirm_password != $param['password']) to_ajax(0, '109');
        $row = $dou->get_row("SELECT * FROM " . $dou->table('user') . " WHERE password='$old_password' AND usertoken='{$usertoken}' LIMIT 1");
        //echo "SELECT * FROM " . $dou->table('user') . " WHERE password='{$param[password]}' AND usertoken='{$usertoken}' LIMIT 1";
        if(!$row) to_ajax(0,'111');
    }
    
    $sql = $dou->update_sql($dou->table('user'), $param, "user_id='{$user_info[user_id]}'");
    $dou->query($sql);
    to_ajax(1, '000', $arr);
}

function coupon_list(){
    $sql = "SELECT * FROM ".$GLOBALS['dou']->table('coupon')." WHERE user_id='{$GLOBALS[user_id]}'";
    $arr['list'] = $GLOBALS['dou']->get_all($sql);
    to_ajax(1, '000', $arr);
}
//使用优惠券
function coupon_use(){
    _check_cart();
    global $cache, $dou, $cachekey_cart, $user_id;
    $cart = $cache->get($cachekey_cart);
    $coupon_id    = I('coupon_id', 0, 'post');
    //if($coupon_id == 0) to_ajax(0,'106');
    //使用优惠券
    if( $coupon_id>0 ){
        $sql = "SELECT * FROM ".$dou->table('coupon')." WHERE coupon_id='{$coupon_id}' AND used_time=0 AND user_id='{$user_id}'";
        $coupon = $dou->get_row( $sql );
        if(!$coupon) to_ajax(0,'308');
        //判断优惠券最小使用金额
        if($cart[total_price_pay] < $coupon[min_price]) to_ajax(0,'307'); 
        //未使用优惠券情况
        if(!isset($cart[coupon])) $cart['total_price_pay'] = $cart['total_price_pay'] - $coupon[coupon_price];
        //已使用优惠券情况
        if(isset($cart[coupon])){
            $cart['total_price_pay'] = $cart['total_price_pay'] + $cart[coupon][coupon_price];
            $cart['total_price_pay'] = $cart['total_price_pay'] - $coupon[coupon_price];
        }
        $cart['coupon'] = $coupon;

    }
    //不使用优惠券
    if($coupon_id == 0 && $cart[coupon][id]>0){
        $cart['total_price_pay'] = $cart['total_price_pay'] + $cart[coupon][coupon_price];
        unset($cart[coupon]);
    }
    $cache->set($cachekey_cart, $cart);
    to_ajax(1, '000', $cache->get($cachekey_cart));
}
//开发票
function invoice_use(){
    _check_cart();
    global $cache, $dou, $cachekey_cart, $user_id;
    $rate = 6/100; //手续费
    $cart = $cache->get($cachekey_cart);
    $invoiced      = i('invoiced', 0, 'post');
    $invoice_title = i('invoice_title','','post');
    //开发票
    if($invoiced == 1 && !isset($cart[invoice])){
        $counter_fee = $cart[total_price_pay]*$rate;
        $cart[total_price_pay] = $cart[total_price_pay] + $counter_fee;
        $cart[invoice] = array('invoiced'=>1, 'invoice_title'=>$invoice_title, 'counter_fee'=>$counter_fee);
    }
    //不开发票
    if($invoiced == 0 && $cart[invoice][invoiced]>0){
        $cart[total_price_pay] = $cart[total_price_pay] - $cart[invoice][counter_fee];
        unset($cart[invoice]);
    }
    $cache->set($cachekey_cart, $cart);
    to_ajax(1, '000', $cart);
}

function cart_info(){
	$cart = $GLOBALS['cache']->get($GLOBALS['cachekey_cart']);
    if(!$cart['list']) $cart['list'] = array();
	to_ajax(1, '000', $cart);
}

//保存购物车
function cart_save(){
    global $user_info,$cachekey_cart;
    $cat_id = i('cat_id','0', 'post');
    //判断商品是否存在
    $cat_info = _cat_info($cat_id);
    //判断购物车是否为空
    $booklist = $_POST['booklist'];
    if(empty($booklist)) to_ajax(0, '201');
    array_multisort(array_column($booklist,'bookdate'),SORT_ASC,$booklist);
    //统计购物车商品总数
    $noon_nums  = array_column($booklist,'noon_num');
    $night_nums = array_column($booklist,'night_num');
    $total_num  = array_sum($noon_nums)+array_sum($night_nums);
    //获取商品价格
    $price_user_type = json_decode($cat_info['price_user_type']); //等级单价
    $price_user_type = isset($price_user_type[$user_info[user_type]]) ? $price_user_type[$user_info[user_type]] : $cat_info['price'];
    $level_discount  = level_discount($user_info[level]);
    $price_discount  = $price_user_type*$level_discount;  //折扣单价

    $cart = array(
        'cat_id'          => $cat_info['cat_id'],
        'cat_name'        => $cat_info['cat_name'],
        'list'            => $booklist,
        'price'           => $cat_info['price'], //原价
        'price_user_type' => $price_user_type, //等级单价
        'price_discount'  => $price_discount,  //折扣单价

        'total_num'       => $total_num,
        'total_price'     => $price_user_type*$total_num, //等级总价
        'total_price_pay' => $price_discount*$total_num,  //折扣总价
        'level_discount'  => $level_discount,
    );
    //保存购物车数据
    $GLOBALS['cache']->set($cachekey_cart, $cart);
    to_ajax(1, '000', $cart);
}

//保存订单
function order_save(){
    global $dou,$cache,$user_info;
    $cart  = _check_cart(); //检查购物车
    $address = _check_address(); //检查收货信息
    _check_user_balance($cart['total_price_pay']); //检查余额
    //保存订单
    $param     = $address;
    $param['user_id']     = $user_info['user_id'];
    $param['user_name']   = $user_info['user_name'];
    $param['cat_id']      = $cart['cat_id'];
    $param['cat_name']    = $cart['cat_name'];
    $param['price']       = $cart['price_user_type'];   //等级单价
    $param['price_discount'] = $cart['price_discount'];  //折扣单价

    $param['total_price'] = $cart['total_price'];  //总价
    $param['total_price_pay'] = $cart['total_price_pay']; //支付价格
    $param['total_num']   = $cart['total_num'];
    $param['add_time']    = time();
    $param['state']       = 1;
    $param['paystate']    = 1;

    //处理下单 start------->>>
    //开发票
    if($cart[invoice][invoiced]){
        $param['invoice']       = $cart[invoice][invoiced];
        $param['invoice_title'] = $cart[invoice][invoice_title];
    } 
    $dou->query( $GLOBALS['dou']->insert_sql($dou->table('order'),$param) );
    foreach($cart['list'] as $k=>$v){
        if($v[bookdate]){
            $param_cat     = $v;
            $param_cat['order_no'] = $param['order_no'];
            $dou->query( $dou->insert_sql($dou->table('order_booking'),$param_cat) );
        }
    }
    _add_user_balance(-$cart['total_price_pay']); //扣除用户余额
    //把优惠券改为已经使用
    if($cart[coupon][coupon_id]) 
        $dou->query( $dou->update_sql($dou->table('coupon'),array('used_time'=>time(),'order_no'=>$param['order_no']), "coupon_id='{$cart[coupon][coupon_id]}'") );
    //清空购物车
    $cache->set($GLOBALS['cachekey_cart'] ,array());
    //end------->>>
    to_ajax(1, '000', $param);
}

function order_list(){
    global $dou;
    $sql = "SELECT * FROM ".$dou->table('order')."WHERE user_id='{$GLOBALS[user_id]}' ORDER BY `add_time`";
    $arr[order] = $dou->get_all($sql);
    if($arr[order]){
        foreach($arr[order] as $k=>$v){
            $arr[order][$k][booking] = $dou->get_all( "SELECT * FROM ".$dou->table('order_booking')." WHERE order_no='$v[order_no]'" );
        }
    }
    to_ajax(1, '000', $arr);
}

//获取用户默认收货地址
function address_default(){
    $sql = "SELECT * FROM " . $GLOBALS['dou']->table('user_address') . " WHERE user_id='{$GLOBALS[user_info][user_id]}' ORDER BY `default`  DESC LIMIT 1";
    $arr = $GLOBALS['dou']->get_row($sql);
    to_ajax(1, '000', $arr);
}
function address_add(){
	global $dou;
    $address = _check_address();
    $address['user_id'] = $GLOBALS['user_id'];
    $dou->query( $dou->insert_sql($dou->table('user_address'),$address) );
    to_ajax(1, '000', $address);
}
function address_update(){
	global $dou,$user_id;
    $address = _check_address();
    $id = i('id','0','post');
    $address['default'] = i('default',0,'post');
    $address['user_id'] = $user_id;
    $dou->query( $dou->update_sql($dou->table('user_address'),$address, " id='$id' AND user_id='$user_id' ") );
    to_ajax(1, '000', $address);
}

// function order_list()
// function order_info()











/***------------------------------------------/
* 内部函数
* --------------------------------------------/
*/
function _user_info($usertoken){
    $sql = "SELECT * FROM " . $GLOBALS['dou']->table('user') . " WHERE usertoken='{$usertoken}' LIMIT 1";
    $row = $GLOBALS['dou']->get_row($sql);
    if($row) return $row;
    return false;
}
function _check_address(){
    $param = array(
        'consignee'=>i('consignee','','post'),
        'sex'=>i('sex','0','post'),
        'province'=>i('province','','post'),
        'city'=>i('city','','post'),
        'area'=>i('area','','post'),
        'address'=>i('address','','post'),
        'mobile'=>i('mobile','','post')
    );
    if(empty($param[consignee])) to_ajax(0,'300');
    if(empty($param[province]))  to_ajax(0,'301');
    if(empty($param[city]))      to_ajax(0,'302');
    if(empty($param[area]))      to_ajax(0,'303');
    if(empty($param[address]))   to_ajax(0,'304');
    if(empty($param[mobile]))    to_ajax(0,'305');
    return $param;
}
function _check_cart(){
    $cart = $GLOBALS['cache']->get($GLOBALS['cachekey_cart']);
    if(!$cart || $cart['total_num'] == 0 || !is_array($cart['list'])) to_ajax(0, '350');
    return $cart;
}
function _check_user_balance($price){
    if($price > $GLOBALS['user_info']['balance']) to_ajax(0,'306');
    return true;
}
function _check_user_hasfield($field,$value){
    global $usertoken, $dou;
    $sql = "SELECT * FROM " . $GLOBALS['dou']->table('user') . " WHERE {$field}='$value' AND usertoken<>'{$usertoken}' LIMIT 1";
    $row = $dou->get_row($sql);
    if($row) return true;
    return false;
}
function _add_user_balance($price){
    global $dou,$user_info;
    $balance = $user_info['balance'];
    if( ($balance+$price) < 0 ) to_ajax(0,'300');
    $dou->query( $dou->update_sql($dou->table('user'), array('balance'=>$balance+$price), "user_id='{$user_info[user_id]}'") );
    $log = array('type'=>'balance','create_time'=>time(), 'user_id'=>$user_info['user_id'], 'action'=>"用户:{$user_info[user_name]}消费了$price" );
    $dou->query( $dou->insert_sql($dou->table('user_log'), $log) );
    return true;
}
function _cat_info($cat_id){
    global $dou;
    $sql = "SELECT * FROM " . $GLOBALS['dou']->table('product_category') . " WHERE cat_id='{$cat_id}' LIMIT 1";
    $cat_info = $GLOBALS['dou']->get_row($sql);
    if(!$cat_info) to_ajax(0, '200');
    return $cat_info;
}